<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
        >
          {{ item.meta.title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          status-icon
          size="large"
        >
          <el-form-item label="景点名" prop="name">
            <el-input v-model="ruleForm.name" @input="checkname" />
          </el-form-item>
          <el-form-item label="简要描述" prop="desc">
            <el-input v-model="ruleForm.desc" type="text" />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input v-model="ruleForm.content" type="textarea" />
          </el-form-item>
          <el-form-item label="景点级别" prop="category">
            <el-radio-group v-model="ruleForm.category">
              <el-radio :label="0">5A</el-radio>
              <el-radio :label="1">4A</el-radio>
              <el-radio :label="2">3A</el-radio>
              <el-radio :label="3">2A</el-radio>
              <el-radio :label="4">1A</el-radio>
              <!-- <el-radio :label="2">vip用户</el-radio> -->
            </el-radio-group>
          </el-form-item>
          <el-form-item label="景点logo" prop="logo" ref="uploadElement">
            <el-upload action="#" list-type="picture-card" :auto-upload="false" :on-remove="handledel"
              :on-change="changeUploadImg" ref="upload" :file-list="fileList" :multiple="true" name="file"
              v-model="fileList" :limit="1" :class="{ hidden: fileList.length == 1 }">
              <el-icon>
                <Plus />
              </el-icon>
              <template #file="{ file }">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <el-icon>
                        <ZoomIn />
                      </el-icon>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handledel(file)">
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </span>
                  </span>
                </div>
              </template>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传 .jpg 或 .png 格式图片，且图片大小不能超过256KB！
                </div>
              </template>
            </el-upload>
            <!-- 放大的图片 -->
            <el-dialog v-model="dialogVisible" top="7vh">
              <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: auto" />
            </el-dialog>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >新增</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, watch } from "vue";
import request from "../../utils/request";
import { ElMessage, ElNotification } from "element-plus";

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
const fileList = ref([]);
const upload = ref(null);

// 移除图片
const handledel = (file) => {
  fileList.value = fileList.value.filter((i) => {
    return i.uid !== file.uid;
  });
};
//展示大图
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

//限制大小
//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changeUploadImg = (file) => {
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  if (!isJPG && !isPNG) {
    ElMessage.error("上传图片只能是 .jpg 或者 .png 格式！");
    // 取消时在文件列表中删除该文件
    upload.value.handleRemove(file);
    return isJPG || isPNG;
  } else if (file.size / 5120 > 1024) {
    ElMessage.error("图片大小不能超过256KB！");
    upload.value.handleRemove(file);
    return false;
  } else {
    fileList.value.push(file);
    rules.logo = [];//清空logo的校验信息
  }
};

let breadList = []; // 路由集合
const route = useRoute();
const router = useRouter();
const getBreadcrumb = (url) => {
  let matched = url.matched;
  //如果不是首页
  if ("Home" == matched[0].name) {
    matched[0].meta = { title: "系统首页" };
  }
  breadList = matched;
};
watch(
  route,
  (newValue, oldValue) => {
    // console.log(222222,newValue)
    getBreadcrumb(newValue);
  },
  { deep: true, immediate: true }
);

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};

//添加景点
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    const formData = new FormData();
    fileList.value.forEach((value, index) => {
      formData.append("imgfile", value.raw);
    });
    formData.append("name", ruleForm.name);
    formData.append("desc", ruleForm.desc);
    formData.append("content", ruleForm.content);
    formData.append("category", ruleForm.category);
    if (valid) {
      console.log("提交更新", fields);
      //发送ajax请求
      request
        .post("/travel/addTravel",formData,{
          headers:{
            "Content-Type":
            "multipart/form-data;charset=UTF-8; boundary=<calculated when request is sent>",
          },
        })
        .then((res) => {
          // 处理响应
          if (res.data.code == "200") {
            ElMessage({
              message: res.data.msg,
              type: "success",
            });
            // formEl.resetFields();
            router.push("/travelInfo");
          } else if (res.data.code == "500") {
            ElMessage({
              message: res.data.msg,
              type: "error",
            });
          }
        });
    } else {
      ElNotification({
        title: "校验失败",
        message: "请重新填写信息",
        type: "error",
      });
    }
  });
};
const ruleForm = reactive({
  // u_id: "",
  name: "",
  desc: "",
  content: "",
  category: 0,
  logo:''
});
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入景点名",
      // trigger: ["blur", "change"], // 不加这行效果一致
    },
    {
      pattern: /^\S*$/, // 正则表达式校验用户名，不允许空格
      message: "用户名中不能有空格",
    },
    // {
    //   pattern: /^[a-zA-Z0-9_]+$/, // 正则表达式校验用户名，只允许字母、数字和下划线
    //   message: "用户名只能包含字母、数字和下划线",
    //   trigger: ["blur", "change"],
    // },
  ],
  desc: [
    {
      required: false,
      message: "请输入简要信息",
      trigger: "blur",
    },
  ],  
  content: [
    {
      required: false,
      message: "请输入内容",
      trigger: "blur",
    },
  ],
  category: [
    {
      required: true,
      message: "请选择景点级别",
      trigger: "change",
    },
  ],
  logo: [
    {
      required: true,
      message: "请上传景点logo",
      trigger: "change",
    },
  ],
});
const ruleFormRef = ref();
</script>

<style>
.hidden .el-upload--picture-card {
  display: none;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
